import { Config } from '../utils/config.js';
import { Token } from '../utils/token.js';
import { util } from '../utils/common.js';

class Base{
  constructor(){
    this.baseRequestUrl = Config.restUrl;
  }
  //当noRefecth为true时，不做未授权重试机制
  request(params, noRefecth){
    var that = this;
    var url = this.baseRequestUrl + params.url;
    if (!params.type){
      params.type = 'GET';
    }
    wx.request({
      url: url,
      data: params.data,
      header: {
        'content-type':'application/json',
        'X-Requested-With': 'XMLHttpRequest',
        'Authorization': tt.getStorageSync('token')
      },
      method: params.type,
      success: function(res) {
        var code = res.statusCode.toString();
        var startChar = code.charAt(0);

        if(res.header.Authorization){
          tt.setStorageSync('token', res.header.Authorization);
        }

        if (startChar == '2'){
          params.sCallBack && params.sCallBack(res.data);
        }else{
          //AOP思想
          if(code == '401'){
            if (!noRefecth){
              that._refetch(params);
            }
          }
          // if (noRefecth){
            params.eCallBack && params.eCallBack(res.data);
          // }
         
        }
      },
      fail: function(err) {
        // Console.log('err',err);
      },
    })
  }
  
  _refetch(param) {
    console.log('失败、未登录',param)
    tt.showModal({
      title: "登录状态过期",
      content: "您当前的登录状态已过期,请重新登录",
      success(res){
        console.log(res)
        if(res.confirm){
          tt.setStorageSync('returnurl', '');
          tt.navigateTo({
            url: '/pages/getphone/getphone'// 指定页面的url
          });
        }
      }
    });
  }
}

export { Base };